//
//  KLMModeSettingController.swift
//  KLM_GN
//
//  Created by Nic on 2025/3/7.
//

import UIKit

enum DeviceSubModeType {
    case AIWork
    case AIRest
    case AIScreen// 阅屏
    case AIEnergySaving// 节能
    case AIOther
    
    case sceneReadWrite
    case sceneScreenTime
    case sceneFocus
    case sceneLight
    case sceneSleep
    case sceneOther
}

enum GlowType {
    case up
    case down
}

private let baseCellId = String(describing: KLMModeCardTimeCell.self)
private let customTimeCellId = String(describing: KLMModeCustomTimeCell.self)
private let observeKey = "contentSize"

class KLMModeSettingController: KLMBaseController {
    
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var containerView: UIView!
    @IBOutlet weak var topView: UIView!
    @IBOutlet weak var sliderView: UIView!
    @IBOutlet weak var timeBtn: UIButton!
    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var sliderToTopViewCons: NSLayoutConstraint!// 1000   8
    @IBOutlet weak var sliderToContainerCons: NSLayoutConstraint!// 250 8
    @IBOutlet weak var colletionViewHCons: NSLayoutConstraint!//245
    
    @IBOutlet weak var lightLabel: UILabel!
    @IBOutlet weak var colorTempLabel: UILabel!
    @IBOutlet weak var lightSlider: KLMVerticalSliderView!
    @IBOutlet weak var colorTempSlider: KLMVerticalSliderView!
    
    /// topView
    @IBOutlet weak var topTipBtn: UIButton!
    @IBOutlet weak var startLabel: UILabel!
    @IBOutlet weak var endLabel: UILabel!
    @IBOutlet weak var startTextField: KLMModeTextField!
    @IBOutlet weak var endTextField: KLMModeTextField!
    @IBOutlet weak var executeBtn: UIButton!
    @IBOutlet weak var executeTextField: KLMModeTextField!
    @IBOutlet weak var lightBtn: UIButton!
    @IBOutlet weak var lightTextField: KLMModeTextField!
    @IBOutlet weak var turnOffBtn: UIButton!
    @IBOutlet weak var turnOffTextField: KLMModeTextField!
    @IBOutlet weak var executeToTimeViewCons: NSLayoutConstraint!// 250
    @IBOutlet weak var executeToLightCons: NSLayoutConstraint!// 1000
    @IBOutlet weak var lightContainerView: UIView!
    @IBOutlet weak var turnOffContainerView: UIView!
    
    var modeType: DeviceModeType
//    var subModeType: DeviceSubModeType
    var glowType: GlowType
    var modeCards: [KLMCard] = []
    
//    let config: KLMSceneConfig?
    let rkScene: KLMRKScene
    let isDown: Bool // 是否是 下发光
    let isAIRestMode: Bool // 是否是 AI模式中的休息模式
    private var popView: YBPopupMenu?
    private var showPopView: Bool = false
    private var popViewSelectIndex: Int?
    var executeWeek: [String]?
    weak var popupTableView: PopupTableView?
    lazy var popViewTitles = [
        "仅一次",
        "周一至周五",
        "每天",
        "法定工作日",
        "自定义"
    ]
    lazy var popViewIcons: [String] = {
        return popViewTitles.map { _ in
            "uncheck"
        }
    }()
    init(modeType: DeviceModeType, glowType: GlowType, rkScene: KLMRKScene) {
        self.modeType = modeType
        self.glowType = glowType
        self.isDown = glowType == .down
        self.rkScene = rkScene
        self.isAIRestMode = rkScene.rkSceneCodeType == .rk_rest_state
        super.init(nibName: "KLMModeSettingController", bundle: nil)
    }
    
    @MainActor required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        initData()
        collectionView.addObserver(self, forKeyPath: observeKey, options: [.new], context: nil)
    }
    // MARK: - 设置初始数据
    func initData() {
        guard let config = rkScene.sceneConfig else { return }
        // AI模式中的休息模式、所有情景模式
        if modeType == .scene || isAIRestMode {
            startTextField.text = isDown ? config.downStartTime : config.upStartTime
            endTextField.text = isDown ? config.downEndTime : config.upEndTime
            let frequency = isDown ? config.downFrequency : config.upFrequency
            if let frequency = frequency {
                // 0未选中 1仅1次 2周1到周5 3每天 4法定工作日 5自定义
                executeTextField.text = ""
                if frequency != 0 && frequency <= popViewTitles.count {
                    executeTextField.text = "\(popViewTitles[frequency - 1])"
                    popViewSelectIndex = frequency - 1
                }
                let week = isDown ? config.downWeek : config.upWeek
                if let week = week {
                    executeWeek = week.map({ String($0) })
                }
                executeBtn.isSelected = frequency != 0
            }
            
            // 情景模式
            if modeType == .scene {
                let fadeUp = isDown ? config.downFadeUp : config.upFadeUp
                if let light = fadeUp, light != 0 {
                    lightTextField.text = "\(light)"
                    lightBtn.isSelected = true
                }
                let fadeDown = isDown ? config.downFadeDown : config.upFadeDown
                if let fadeDown = fadeDown, fadeDown != 0 {
                    turnOffTextField.text = "\(fadeDown)"
                    turnOffBtn.isSelected = true
                }
            }
        }
        // 亮度、色温
        let brightness = isDown ? config.downBrightness: config.upBrightness
        let temperature = isDown ? config.downTemperature: config.upTemperature
        if let brightness = brightness {
            lightSlider.configure(value: CGFloat(brightness))
        }
        if let temperature = temperature {
            colorTempSlider.configure(value: CGFloat(temperature))
        }
        // 定时设置
        let duration = isDown ? config.downStateDuration: config.upStateDuration
        if let duration = duration, duration != 0 {
            guard let cardIndex = modeCards.firstIndex(where: {$0.title == "\(duration)"}) else {
                // 找不到，那就是自定义的时间，替换最后一个title，并选中
                let index = modeCards.count - 1
                modeCards[index].select = true
                modeCards[index].title = "\(duration)"
                collectionView.reloadItems(at: [IndexPath(item: index, section: 0)])
                return
            }
            modeCards[cardIndex].select = true
            collectionView.reloadItems(at: [IndexPath(item: cardIndex, section: 0)])
        }
    }
    // MARK: - 合并数据
    func mergeConfigData() -> (Bool, [String: Any]) {
        // 情景模式，sceneConfig为nil
//        guard let config = rkScene.sceneConfig else { return (false, ["error" : "页面出错了"])}
        // AI模式中的休息模式、所有情景模式
        if modeType == .scene || isAIRestMode {
            guard let start = startTextField.text, !start.isEmpty else { return (false, ["error" : "开始时间不能为空"]) }
            guard let end = endTextField.text, !end.isEmpty else { return (false, ["error" : "结束时间不能为空"]) }
            if start == end { return (false, ["error" : "开始时间与结束时间不能相同"]) }
            guard let frequency = popViewSelectIndex, let executeText = executeTextField.text, !executeText.isEmpty else { return (false, ["error" : "请选择执行频率"]) }
            if executeText == popViewTitles.last {
                guard let executeWeek = executeWeek else { return (false, ["error" : "请选择执行频率自定义时间"]) }
            }
            if modeType == .scene {
                // 情景模式
                guard let light = lightTextField.text, !light.isEmpty else { return (false, ["error" : "渐亮时间不能为空"]) }
                guard let off = turnOffTextField.text, !off.isEmpty else { return (false, ["error" : "渐灭时间不能为空"]) }
            }
        }
        guard let card = modeCards.first(where: { $0.select == true }) else { return (false, ["error" : "请选择定时设置时间"]) }
        
        var dict: [String: Any] = [:]
        // 亮度、色温、定时设置
        if isDown {
            dict["downBrightness"] = Int(lightSlider.value)
            dict["downTemperature"] = Int(colorTempSlider.value)
            dict["downStateDuration"] = Int(card.title)
        } else {
            dict["upBrightness"] = Int(lightSlider.value)
            dict["upTemperature"] = Int(colorTempSlider.value)
            dict["upStateDuration"] = Int(card.title)
        }
        if modeType == .scene || isAIRestMode {
            // 执行频率 0未选中 1仅1次 2周1到周5 3每天 4法定工作日 5自定义
            let index = popViewSelectIndex! + 1
            // 开始、结束、执行频率
            if isDown {
                dict["downStartTime"] = startTextField.text!
                dict["downEndTime"] = endTextField.text!
                dict["downFrequency"] = Int(index)
                
            } else {
                dict["upStartTime"] = startTextField.text!
                dict["upEndTime"] = endTextField.text!
                dict["upFrequency"] = Int(index)
            }
            
            if index == popViewTitles.count {
                /// 如果是自定义
                if isDown {
                    dict["downWeek"] = executeWeek?.joined(separator: "")
                } else {
                    dict["upWeek"] = executeWeek?.joined(separator: "")
                }
            }
            if modeType == .scene {
                // 情景模式
                if isDown {
                    dict["downFadeUp"] = Int(lightTextField.text!)
                    dict["downFadeDown"] = Int(turnOffTextField.text!)
                } else {
                    dict["upFadeUp"] = Int(lightTextField.text!)
                    dict["upFadeDown"] = Int(turnOffTextField.text!)
                }
                
                if rkScene.sceneConfig == nil {
                    // 初始化一个默认参数的对象，补齐所有key
                    let config = KLMSceneConfig(downBrightness: 0, upBrightness: 0, upTemperature: 2700, downTemperature: 2700, upStartTime: "", upEndTime: "", downStartTime: "", downEndTime: "", downFrequency: 0, upFrequency: 0, upFadeUp: 0, upFadeDown: 0, downFadeUp: 0, downFadeDown: 0, upStateDuration: 0, downStateDuration: 0, upWeek: "", downWeek: "")
                    if let configDict = config.toDictionary() {
                        dict = configDict.merging(dict) { _, new in
                            new
                        }
                    }
                }
            }
        }
        return (true, dict)
    }
    // MARK: - viewDidLoadConfig
    override func viewDidLoadConfig() {
        super.viewDidLoadConfig()
        scrollView.showsVerticalScrollIndicator = false
        
        topTipBtn.isEnabled = false
        topTipBtn.configStyle(with: "时间段设置", font: UIFont(safeName: "PingFangSC-Bold", size: 18), titleColor: rgba(38, 38, 38, 1), state: .disabled)
        startLabel.configStyle(with: "开始", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: rgba(38, 38, 38, 1))
        endLabel.configStyle(with: "结束", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: rgba(38, 38, 38, 1))
        executeBtn.configStyle(with: "执行频率", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: rgba(38, 38, 38, 1), image: "uncheck")
        executeBtn.configStyle(image: "check", state: .selected)
        lightBtn.configStyle(with: "渐亮时间", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: rgba(38, 38, 38, 1), image: "uncheck")
        lightBtn.configStyle(image: "check", state: .selected)
        turnOffBtn.configStyle(with: "渐灭时间", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: rgba(38, 38, 38, 1), image: "uncheck")
        turnOffBtn.configStyle(image: "check", state: .selected)
        
        executeBtn.isUserInteractionEnabled = false
        lightBtn.isUserInteractionEnabled = false
        turnOffBtn.isUserInteractionEnabled = false
        
        startTextField.placeholder = "选择时间"
//        startTextField.configKeyboard(dateFormatString: "MM/dd HH:mm", datePickerMode: .time)
        startTextField.delegate = self
        
        endTextField.delegate = self
        endTextField.placeholder = "选择时间"
//        endTextField.configKeyboard(dateFormatString: "MM/dd HH:mm")
        
        executeTextField.placeholder = "选择执行频率"
        executeTextField.delegate = self
        
        lightTextField.placeholder = "请输入时间(秒s)"
        lightTextField.keyboardType = .numberPad
        lightTextField.delegate = self
        
        turnOffTextField.placeholder = "请输入时间(秒s)"
        turnOffTextField.keyboardType = .numberPad
        turnOffTextField.delegate = self
        
        timeBtn.isEnabled = false
        timeBtn.configStyle(with: "定时设置", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: rgba(38, 38, 38, 1), image: "Mode_time", state: .disabled)
        
        lightSlider.valueChanged = { [weak self] value, slider in
            guard let self = self else { return }
            self.lightLabel.text = "亮度\(Int(value))\(slider.unit)"
            print("con1中值变化: \(value)")
        }
        colorTempSlider.valueChanged = { [weak self] value, slider in
            guard let self = self else { return }
            print("con2中值变化: \(value)")
            self.colorTempLabel.text = "色温\(Int(value))\(slider.unit)"
        }
        
        lightLabel.configStyle(with: "亮度", font: UIFont(safeName: "PingFangSC-Regular", size: 14), titleColor: rgba(38, 38, 38, 1))
        colorTempLabel.configStyle(with: "色温", font: UIFont(safeName: "PingFangSC-Regular", size: 14), titleColor: rgba(38, 38, 38, 1))
        
        lightSlider.configure(value: 0, unit: "%", iconName: "light")
        lightSlider.setGradientColors(start: rgba(251, 138, 3, 1), end: rgba(255, 244, 231, 1))
        colorTempSlider.configure(value: 2700, unit: "K", iconName: "dark", minValue: 2700, maxValue: 6500, step: 100)
        colorTempSlider.setGradientColors(start: rgba(251, 138, 3, 1), end: rgba(254, 191, 105, 1))
        
        // AI模式中的休息模式、所有情景模式
        if modeType != .scene && !isAIRestMode {
            topView.isHidden = true
            sliderToTopViewCons.priority = .defaultLow
            sliderToContainerCons.priority = .required
            modeCards = KLMCard.aiWorkModeCards()
        } else {
            topView.isHidden = false
            sliderToTopViewCons.priority = .required
            sliderToContainerCons.priority = .defaultLow
            
            modeCards = KLMCard.aiRestModeCards()
            if isAIRestMode {
                // 休息模式
                lightContainerView.isHidden = true
                turnOffContainerView.isHidden = true
                executeToTimeViewCons.priority = .required
                executeToLightCons.priority = .defaultLow
            } else {
                lightContainerView.isHidden = false
                turnOffContainerView.isHidden = false
                executeToTimeViewCons.priority = .defaultLow
                executeToLightCons.priority = .required
            }
        }
        collectionView.register(UINib(nibName: "KLMModeCardTimeCell", bundle: nil), forCellWithReuseIdentifier: baseCellId)
        collectionView.register(UINib(nibName: "KLMModeCustomTimeCell", bundle: nil), forCellWithReuseIdentifier: customTimeCellId)
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    @IBAction func tapExecute(_ sender: UIButton) {
        sender.isSelected.toggle()
    }
    @IBAction func tapLight(_ sender: UIButton) {
        sender.isSelected.toggle()
//        sender.isSelected = !sender.isSelected
    }
    @IBAction func tapTurnOff(_ sender: UIButton) {
        sender.isSelected.toggle()
//        sender.isSelected = !sender.isSelected
    }
    // MARK: - KVO监听
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == observeKey, let _ = object as? UICollectionView, let newSize = change?[.newKey] as? CGSize {
            // 更新高度约束
            colletionViewHCons.constant = newSize.height
        }
    }
    override func setNavBarStyle() {
        customNavBarAppearance(barTintColor: .white, titleColor: nil)
    }
    // MARK: - 移除KVO监听
    deinit {
        collectionView?.removeObserver(self, forKeyPath: observeKey)
    }
}

// MARK: - UICollectionViewDataSource
extension KLMModeSettingController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return modeCards.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let card = modeCards[indexPath.item]
        if card.subType == .customTime {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: customTimeCellId, for: indexPath) as! KLMModeCustomTimeCell
            cell.modeCard = card
            cell.customTimeEndEditingBlock = {[weak self] text in
                guard let self = self else { return }
                if let text = text, text.count > 0 {
                    // 取消所有选中
                    for index in modeCards.indices {
                        modeCards[index].select = false
                    }
                    modeCards[indexPath.item].title = text
                    modeCards[indexPath.item].select = true
                    collectionView.reloadData()
                }
            }
            return cell
        } else {
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: baseCellId, for: indexPath) as! KLMModeCardTimeCell
            cell.modeCard = card
            return cell
        }
    }
}
// MARK: - UICollectionViewDelegateFlowLayout
extension KLMModeSettingController: UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        // 点击卡片
        if modeCards[indexPath.item].subType == .customTime {
            let cell = collectionView.cellForItem(at: indexPath) as! KLMModeCustomTimeCell
            cell.startEditing()
        } else {
            if !modeCards[indexPath.item].select {
                for index in modeCards.indices {
                    modeCards[index].select = false
                }
                modeCards[indexPath.item].select = true
                collectionView.reloadData()
            }
        }
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 19, right: 0)
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 16
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 14
    }
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
//        let inset = self.collectionView(collectionView, layout: collectionViewLayout, insetForSectionAt: indexPath.section)
//        let sizeWidth = collectionView.width - inset.left - inset.right
        let sizeWidth = KLMScreenW - 16*2
        if modeCards.count % 2 == 0 {
            let itemW = (sizeWidth - 14) / 2
            return CGSize(width: floor(itemW), height: 88)
        }
        let mode = modeCards[indexPath.item]
        if mode.subType == .customTime {
            return CGSize(width: floor(sizeWidth), height: 88)
        } else {
            let itemW = (sizeWidth - 14) / 2
            return CGSize(width: floor(itemW), height: 88)
        }
    }
}

// MARK: - UITextFieldDelegate
extension KLMModeSettingController: UITextFieldDelegate {
    
    func textFieldDidEndEditing(_ textField: UITextField) {
        var select: Bool = false
        if let text = textField.text, !text.isEmpty {
            select = true
        }
        if textField == lightTextField {
            lightBtn.isSelected = select
        }
        if textField == turnOffTextField {
            turnOffBtn.isSelected = select
        }
    }
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == executeTextField {
            showPopView = true
            showSelect(on: textField, showPopView: showPopView)
            return false
        }
        if textField == startTextField || textField == endTextField {
            showCustomDatePicker(
                sourceView: textField,
                dateFormat: "HH:mm",
                showUnits: true
            ) { date, dateFormatString  in
                print("选择时间:", date, dateFormatString)
                textField.text = dateFormatString
            }
            return false
        }
        return true
    }
    
    func showSelect(on textField: UITextField, showPopView: Bool) {
        
        if let popView = popView { ///弹过弹框
            popView.delegate = self
            if showPopView {
                popView.show()
            } else {
                popView.dismiss()
            }
        } else { ///没弹过
            if let popViewSelectIndex = popViewSelectIndex {
                popViewIcons[popViewSelectIndex] = "check"
            }
            YBPopupMenu.showRely(on: textField, titles: popViewTitles, icons: popViewIcons, menuWidth: textField.width) {[weak self] popupMenu in
                guard let self = self else { return }
                popupMenu?.priorityDirection = .none
                popupMenu?.arrowHeight = 0
                popupMenu?.minSpace = textField.convert(view.frame.origin, to: view).x
                popupMenu?.dismissOnSelected = false
                popupMenu?.isShadowShowing = false
                popupMenu?.delegate = self
                popupMenu?.cornerRadius = 8
                self.popView = popupMenu
                self.showPopView = true
            }
        }
    }
}
// MARK: - YBPopupMenuDelegate
extension KLMModeSettingController: YBPopupMenuDelegate {
    func ybPopupMenu(_ ybPopupMenu: YBPopupMenu!, didSelectedAt index: Int) {
//        if let popViewSelectIndex = popViewSelectIndex, popViewSelectIndex == index {
//            if index == ybPopupMenu.titles.count - 1 {
//                // 自定义，弹出周一至周日
//                showSelectList()
//                return
//            }
//        }
        if index == ybPopupMenu.titles.count - 1 {
            // 自定义，弹出周一至周日
            showSelectList()
            return
        }
        let title = ybPopupMenu.titles[index]
        executeTextField.text = title as? String
        showPopView = false
        var images = Array(repeating: "uncheck", count: ybPopupMenu.images.count)
        images[index] = "check"
        popViewIcons = images
        
        ybPopupMenu.setValue(images, forKeyPath: "images")
        ybPopupMenu.tableView.reloadSections(IndexSet(integer: 0), with: .fade)
        
        if !executeBtn.isSelected {
            executeBtn.isSelected = true
        }
        popViewSelectIndex = index
        
        // 延迟 2 秒后执行代码
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            ybPopupMenu.dismiss()
        }
    }
    // MARK: - 自定义，底部弹框
    func showSelectList() {
        let config = PopupAppearance(
            maskViewColor: .black.withAlphaComponent(0.7),
            cellHeight: 48,
            maxTableViewHeight: 501,
            animationType: .slideFromBottom
        )

        let popup = PopupTableView(
            position: .explicit(
                frame: CGRect(x: 0, y: KLMScreenH - 501, width: KLMScreenW, height: 501),
                direction: .up
            ),
            appearance: config
        )
        popupTableView = popup
        
        popup.backgroundColor = .white
        popup.tableView.separatorStyle = .none
        let weeks = [
            "星期一",
            "星期二",
            "星期三",
            "星期四",
            "星期五",
            "星期六",
            "星期日",
        ]
        var roleItems: [PopupItem] = []
        for (index, title) in weeks.enumerated() {
            var select = false
            if let executeWeek = executeWeek, index < executeWeek.count {
                select = executeWeek[index] == "1"
            }
            roleItems.append(PopupItem(title: title, subtitle: "", rightNormalIcon: "Role_no_select", rightSelectedIcon: "Role_select", selected: select))
        }
        
        popup.updateItems(roleItems)
        popup.delegate = self
        
        popup.show()
    }
}
// MARK: - PopupTableViewDelegate
extension KLMModeSettingController: PopupTableViewDelegate {
    func popupTableView(_ popupTableView: PopupTableView, didTapRightButtonAt indexPath: IndexPath) {
        popupTableView.delegate?.popupTableView(popupTableView, didSelectRowAt: indexPath)
    }
    func popupTableView(_ popupTableView: PopupTableView, didSelectRowAt indexPath: IndexPath) {
        popupTableView.items[indexPath.row].selected = !popupTableView.items[indexPath.row].selected
        popupTableView.tableView.reloadRows(at: [indexPath], with: .fade)
    }
    func footerView(for popupTableView: PopupTableView) -> UIView? {
        let container = UIView()
        let cancelButton = UIButton(type: .custom)
        cancelButton.configStyle(with: "取消", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: rgba(38, 38, 38, 1))
        cancelButton.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        cancelButton.layer.cornerRadius = 22.0
        cancelButton.layer.masksToBounds = true
        cancelButton.backgroundColor = rgba(247, 247, 247, 1)
        
        let confirmButton = UIButton(type: .custom)
        confirmButton.configStyle(with: "确定", font: UIFont(safeName: "PingFangSC-Medium", size: 16), titleColor: .white)
        confirmButton.addTarget(self, action: #selector(confirmAction), for: .touchUpInside)
        confirmButton.layer.cornerRadius = 22.0
        confirmButton.layer.masksToBounds = true
        confirmButton.backgroundColor = appMainThemeColor
        
        container.addSubview(cancelButton)
        container.addSubview(confirmButton)
        
        cancelButton.snp.makeConstraints { make in
            make.leading.equalToSuperview().offset(26)
            make.top.equalToSuperview().offset(16)
            make.trailing.equalTo(confirmButton.snp.leading).offset(-16)
            make.bottom.equalToSuperview().offset(-16)
//            make.height.equalTo(44)
        }
        confirmButton.snp.makeConstraints { make in
            make.trailing.equalToSuperview().offset(-16)
            make.width.top.bottom.equalTo(cancelButton)
        }
        container.frame = CGRect(x: 0, y: 0, width: popupTableView.width, height: 76)
        return container
    }
    func headerHeight(for popupTableView: PopupTableView) -> CGFloat {
        48
    }
    func headerView(for popupTableView: PopupTableView) -> UIView? {
        let label = UILabel()
        label.configStyle(with: "自定义", font: UIFont(safeName: "PingFangSC-Medium", size: 14), titleColor: rgba(141, 141, 141, 1))
        label.textAlignment = .center
        return label
    }
    
    @objc func cancelAction() {
        popupTableView?.dismiss()
    }
    // MARK: - 频率，自定义，确定按钮事件
    @objc func confirmAction() {
        executeWeek = popupTableView!.items.map({ $0.selected ? "1" : "0" })
        popupTableView?.dismiss()
        
        popViewSelectIndex = popViewTitles.count - 1
        executeTextField.text = popViewTitles.last
        executeBtn.isSelected = true
        var icons = popViewTitles.map { _ in
            "uncheck"
        }
        icons[icons.count - 1] = "check"
        popViewIcons = icons
        
        popView?.setValue(icons, forKeyPath: "images")
        popView?.tableView.reloadSections(IndexSet(integer: 0), with: .fade)
        // 延迟 2 秒后执行代码
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
            self.popView?.dismiss()
        }
    }
}
